package com.kingbi.common;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.kingbi.util.ConstantFiles.UserConstant;

public class SessionFilter extends HttpServlet implements Filter
{

    private static final long serialVersionUID = 1L;

    private FilterConfig filterConfig;

    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
            throws IOException, ServletException
    {
        try
        {
            // 进行请求和响应的类型转换
            HttpServletRequest httpRequest = (HttpServletRequest) arg0;
            HttpServletResponse httpResponse = (HttpServletResponse) arg1;

            String currentURL = httpRequest.getRequestURI();// 取得根目录所对应的绝对路径:
            String targetURL = currentURL
                    .substring(currentURL.indexOf("/", 1), currentURL.length()); // 截取到当前文件名用于比较
            if(!"/faces/login/login.jsf".equals(targetURL)
                    && !"/faces/login/login.faces".equals(targetURL)
                    && !"/faces/login/validLogin.jsp".equals(targetURL)
                    && !"/faces/login/logOff.jsp".equals(targetURL)
                    && !"/faces/login/step.jsp".equals(targetURL)
                    && !"/loadEcer.jsf".equals(targetURL)
                    && !"/faces/login/domainJump.jsf".equals(targetURL))
            {
                if(httpRequest.getSession(false) == null
                        || httpRequest.getSession(false).getAttribute(UserConstant.USER_MAP_KEY_ID) == null)
                {
                    httpResponse.sendRedirect(httpRequest.getContextPath()
                            + "/faces/login/step.jsp");
                    httpRequest = null;
                }
                else
                {
                    arg2.doFilter(arg0, arg1);
                }
            }
            else
            {
                arg2.doFilter(arg0, arg1);
            }
        }
        catch (ServletException sx)
        {
            filterConfig.getServletContext().log(sx.getMessage());
        }
        catch (IOException iox)
        {
            filterConfig.getServletContext().log(iox.getMessage());
        }
    }

    public void init(FilterConfig arg0) throws ServletException
    {
        this.filterConfig = arg0;
    }

}
